package com.yjz.middleware.netty.codec;

import com.alibaba.fastjson.JSON;
import com.yjz.middleware.netty.Student;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.util.CharsetUtil;

import java.util.List;
/**
 * @desc: 学生类编码解码器
 * @author: yuanjz@deepblueai.com
 * @date: 2019/5/9 16:34
 */
public class StudentCodec extends ByteToMessageCodec<Student> {
  @Override
  protected void encode(ChannelHandlerContext channelHandlerContext, Student student, ByteBuf byteBuf) throws Exception {
    byteBuf.writeBytes(student.toString().getBytes(CharsetUtil.UTF_8));
    channelHandlerContext.flush();
  }

  @Override
  protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
    if(byteBuf.isReadable()){
      String  studentStr=byteBuf.toString(CharsetUtil.UTF_8);
      list.add(JSON.parseObject(studentStr,Student.class));
      channelHandlerContext.flush();
    }

  }
}
